package cn.wgx.safetyhelmet.handler;

import cn.wgx.safetyhelmet.handler.exception.BaseException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JSONObject jsonHandler(Exception e){
        JSONObject jsonObject = new JSONObject();
        if(e instanceof BaseException){
            BaseException baseException = (BaseException) e;
            jsonObject.put("msg", baseException.getMsg());
            jsonObject.put("code", baseException.getCode());
            jsonObject.put("tip", "自定义错误.");
        }else{
            jsonObject.put("msg", e.getMessage());
            jsonObject.put("code",e.getLocalizedMessage());
            jsonObject.put("tip", ".");

        }
        return jsonObject;
    }
}
